package com.yihu.wlyy.service.app.team;

import com.yihu.wlyy.entity.doctor.team.admin.AdminTeam;
import com.yihu.wlyy.entity.doctor.team.admin.AdminTeamMember;
import com.yihu.wlyy.repository.DrAdminTeamDao;
import com.yihu.wlyy.repository.DrAdminTeamMemberDao;
import com.yihu.wlyy.service.BaseService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

/**
 * 医生行政团队服务。
 *
 * @author Sand
 */
@Component
@Transactional
public class DrAdminTeamService extends BaseService {
    @Autowired
    DrAdminTeamDao teamDao;

    @Autowired
    DrAdminTeamMemberDao memberDao;

    //-----------------Team Operation----------------------
    public long getTeamCount() {
        return teamDao.count();
    }

    public AdminTeam createTeam(String teamName, String orgCode) {
        AdminTeam team = new AdminTeam();
        team.setName(teamName);
        team.setOrgCode(orgCode);
        team.setAvailable(true);
        team.setCreateTime(new Date());

        saveTeam(team);

        return team;
    }

    public AdminTeam getTeam(long id) {
        AdminTeam team = teamDao.findOne(id);
        return team;
    }

    public AdminTeam updateTeam(long teamId, String teamName, String orgCode) {
        AdminTeam team = getTeam(teamId);
        if (team != null) {
            if (teamName != null) team.setName(teamName);
            if (orgCode != null) team.setOrgCode(orgCode);

            saveTeam(team);
        }

        return team;
    }

    //-----------------Member Operation----------------------
    public void addMember(long teamId, long doctorId, boolean isLeader, String role){
        AdminTeamMember member = new AdminTeamMember();
        member.setTeamId(teamId);
        member.setDoctorId(doctorId);
        member.setJoinTime(new Date());
        member.setLeader(isLeader);

        saveMember(member);
    }

    public void removeMember(long teamId, long doctorId){
        AdminTeamMember member = memberDao.findByTeamIdAndDoctorIdOrderByDoctorIdAsc(teamId, doctorId);
        if(member != null) memberDao.delete(member);
    }

    public List<AdminTeamMember> getMembers(long teamId){
        return memberDao.findByTeamId(teamId);
    }

    private void saveTeam(AdminTeam team) {
        teamDao.save(team);
    }

    private void saveMember(AdminTeamMember member){
        memberDao.save(member);
    }
}
